package com.bjtang.book.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bjtang.book.entiy.SysUser;
import com.bjtang.book.service.MyService;
import com.bjtang.book.service.SysUserDtoService;
import com.bjtang.book.service.SysUserService;

@Service
@Transactional(rollbackFor = Exception.class)
public class SysUserDtoServiceImpl implements SysUserDtoService {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private MyService myService;

	@Override
	public Long addUser(SysUser sysUser) {
		// 注入创建人
		sysUser.setFounder(myService.getMyselfId());
		boolean save = sysUserService.save(sysUser);
		if (save)
			return sysUser.getUserId();

		return 0L;
	}

	@Override
	public Long deleteUserById(Long userId) {
		// 删除用户
		boolean removeById = sysUserService.removeById(userId);
		if (removeById)
			return userId;
		else
			throw new RuntimeException("删除用户异常");
	}

	@Override
	public SysUser updateUserById(SysUser sysUser) {
		// 数据判断,是否有该用户
		SysUser retuUser = new SysUser();
		SysUser user = sysUserService.getById(sysUser.getUserId());
		if (user == null) {
			retuUser.setUserId(-1L);
			return retuUser;
		}
		sysUser.setUpdateBy(myService.getMyselfId());
		boolean save = sysUserService.saveOrUpdate(sysUser);
		if (save)
			return sysUser;
		retuUser.setUserId(0L);
		return retuUser;
	}

	@Override
	public List<SysUser> selectUsers() {
		return sysUserService.list();
	}

	@Override
	public String selectUserNameById(Long userId) {
		SysUser user = sysUserService.getById(userId);
		return user.getName();
	}
	
	@Override
	public SysUser selectUserAddressById(Long userId) {
		SysUser user = sysUserService.getById(userId);
		user.setEmail(null);
		user.setLoginName(null);
		user.setFounder(null);
		user.setCreationTime(null);
		user.setUpdateBy(null);
		user.setUpdateTime(null);
		return user;
	}

	@Override
	public List<SysUser> selectUserNameByIdList(List<Long> userIdList) {
		// TODO Auto-generated method stub
		userIdList.add(-1L);
		List<SysUser> list = sysUserService.lambdaQuery().in(SysUser::getUserId, userIdList).eq(SysUser::getStatus, 0)
				.list();
		for (int i = 0; i < list.size(); i++) {
			list.get(i).setEmail(null);
			list.get(i).setLoginName(null);
			list.get(i).setPhone(null);
			list.get(i).setUserAddress(null);
		}
		return list;
	}



}
